import { first } from 'lodash'
import { point as turfPoint, polygon } from '@turf/turf'
import booleanPointInPolygon from '@turf/boolean-point-in-polygon'
import Store from '@/store'
const $store = Store.getters

/**
 * 获取区域在线人数
 */
export function getPersonAndCarCount(orignList) {
  let result = sumCardCountByArea(orignList, $store.onLinePersonList, {
    countKey: 'personnelCount'
  })

  if ($store.onLineCarList.length) {
    result = sumCardCountByArea(result, $store.onLineCarList, {
      countKey: 'carCount'
    })
  }

  return result
}
export function getDeptCount() {
  const deptList = [...$store.onLinePersonList, ...$store.onLineCarList]
  return deptList.reduce((result, card) => {
    const index = result.findIndex((item) => item.key === card.deptId)
    const key = card.id.includes('person-') ? 'personnelCount' : 'carCount'
    if (index > -1) {
      result[index][key] += 1
    } else {
      result.push({
        key: card.deptId,
        personnelCount: 0,
        carCount: 0,
        [key]: 1
      })
    }

    return result
  }, [])
}

export function sumCardCountByArea(areaArray, cardList, { countKey = 'count' } = {}) {
  const result = [...areaArray.map((item) => ({ ...item, [countKey]: 0 }))]

  if (!cardList.length) {
    return result
  }
  cardList.forEach((person) => {
    result.forEach((item) => {
      if (isInPolygon(person, item.boundary)) {
        item[countKey] += 1
      }
    })
  })
  return result
}

export function getPolygonOneStr(str) {
  const array = JSON.parse(sliceJSONParseStr(str || '[]'))
  if (!array.length) {
    return null
  }

  const towArray = array.reduce((accumulator, currentValue, index) => {
    // 计算当前元素应该属于哪个子数组
    const chunkIndex = Math.floor(index / 3)

    // 如果当前子数组还不存在，则创建它
    if (!accumulator[chunkIndex]) {
      accumulator[chunkIndex] = []
    }

    // 将当前元素添加到对应的子数组中
    if (index % 3 !== 2) {
      accumulator[chunkIndex].push(currentValue)
    }

    // 返回累加器，以便进行下一次迭代
    return accumulator
  }, [])

  return getPolygon(towArray)
}
export function getPolygon(fenceCoordinates) {
  const formatCoords = [[...fenceCoordinates, first(fenceCoordinates)]]

  return polygon(formatCoords)
}

function getPoint({ longitude, latitude }) {
  return turfPoint([longitude, latitude])
}
export function isInPolygon(pointObj, polygonStr, item) {
  const polygon = getPolygonOneStr(polygonStr, item)
  if (!polygon) {
    return false
  }

  return booleanPointInPolygon(getPoint(pointObj), polygon)
}

export function sliceJSONParseStr(str) {
  if (!str) {
    return '[]'
  }
  return str.replace(/\b\d+(\.\d+)?\b/g, (match) => {
    return match.slice(0, 16)
  })
}
